#GandCrab string deobfuscator - a script for IDA

import idautils 
import idc

def is_hex_val(op_val):
	op_len = len(op_val)
	if op_len < 2:
		return False
	if op_val[op_len-1] != 'h':
		return False
	op_val = op_val[:op_len - 1]
	try:
		int(op_val, 16)
	except:
		return False
	return True

def split_and_convert( seq ):
	n = 2
	my_str = ""
	while seq:
		next_val = int(seq[:n],16)
		if next_val != 0:
			my_str = chr(next_val) + my_str
		seq = seq[n:]
	return my_str
		
def hex_to_str(op_val):
	if not is_hex_val(op_val):
		return ""
	op_val = op_val[:len(op_val) - 1] #remove the 'h' at the end
	#if the number of chars is not even, pad it with zero:
	if (len(op_val)  % 2) == 1:
		op_val = '0' + op_val
	my_str = split_and_convert( op_val )
	return my_str

	
for seg_ea in idautils.Segments():
	for head in idautils.Heads(seg_ea, idc.SegEnd(seg_ea)):
		if idc.isCode(idc.GetFlags(head)):        
			mnem = idc.GetMnem(head)
			op_type1 = idc.GetOpType(head,0)
			op_type2 = idc.GetOpType(head,1)
			if mnem == 'mov' and op_type1 == 4 and op_type2 == 5:
				op_val = idc.GetOpnd(head,1)
				ostr = hex_to_str(op_val)
				if len(ostr) > 0:
					MakeRptCmt(head, ostr)
					print "%08x : %s" % (head, ostr)
					
